package com.karaku.karaku_collector.collector;

import android.os.Handler;

import com.google.gson.annotations.SerializedName;
import com.karaku.karaku_collector.LocalSetting;
import com.karaku.karaku_collector.collector.model.DynamicKey;
import com.karaku.karaku_collector.util.MyBatteryManager;

/**
 * Created by guopi on 2017/10/28 0028.
 */

public class HeartbeatManager {

    private static HeartbeatManager instance;

    public static HeartbeatManager getInstance() {
        if (instance == null) {
            instance = new HeartbeatManager();
        }
        return instance;
    }

    private boolean stopped = true;
    private HeartbeatModel model = new HeartbeatModel();
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (stopped) {
                return;
            }
            heartbeat();
            delayAndRun();
        }
    };

    private HeartbeatManager() {

    }

    public void start() {
        stopped = false;
        handler.removeCallbacksAndMessages(null);
        delayAndRun();
    }

    public void stop() {
        stopped = true;
        handler.removeCallbacksAndMessages(null);
    }

    private void delayAndRun() {
        handler.postDelayed(runnable, 5 * 1000);
    }

    private void heartbeat() {
        model.roomId = LocalSetting.getInstance().getRoomId();
        model.direction = LocalSetting.getInstance().getDirection();
        DynamicKey key = CollectorManager.getInstance().getDynamicKey();
        model.uid = key != null ? key.uid : 0;
        model.collectorStat = CollectorStateManager.getInstance().getStat();
        model.batteryStat = MyBatteryManager.getInstance().getStat();
        model.networkQuality = CollectorInfoManager.getInstance().getNetworkQuality();
        model.streamStat = CollectorInfoManager.getInstance().getUploadVideoStat();
        CollectorApi.heartbeat(model, null);
    }

    static class HeartbeatModel {
        @SerializedName("roomId")
        public String roomId;
        @SerializedName("uid")
        public int uid;
        @SerializedName("direction")
        public int direction;
        @SerializedName("collectorStat")
        public CollectorStateManager.CollectorStat collectorStat;
        @SerializedName("batteryStat")
        public MyBatteryManager.BatteryStat batteryStat;
        @SerializedName("networkQuality")
        public CollectorInfoManager.NetworkQualityStat networkQuality;
        @SerializedName("streamStat")
        public CollectorInfoManager.UploadVideoStat streamStat;
    }
}